// pages/individual-edit/index.js
import { Serve } from '../../utils/index'
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		id: '',
		identification: '',
		name: '',
		username: '',
		password: '',
		avatar: '',
	},

	async chooseAvatar(e) {
		const _this = this
		const { avatarUrl } = e.detail
		const arr = avatarUrl.split('.')
		const suffix = arr[arr.length - 1]
		const openid = wx.getStorageSync('openid')
		this.setData({ avatar: avatarUrl })
		wx.showLoading({ title: '更换头像', mask: true })
		await wx.cloud.uploadFile({
			cloudPath: `${openid}/avatar.${suffix}`,
			filePath: avatarUrl,
			success(res) {
				_this.setData({ avatar: res.fileID })
			},
			fail(err) {
				console.log('更换错误', err)
			},
		})
		wx.hideLoading()
	},

	handleNameInput(e) {
		this.setData({ name: e.detail.value })
	},

	handleIdentificationInput(e) {
		this.setData({ identification: e.detail.value })
	},

	handleUsernameInput(e) {
		this.setData({ username: e.detail.value })
	},

	handlePasswordInput(e) {
		this.setData({ password: e.detail.value })
	},

	async updateUser() {
    const { id, name, identification, username, password, avatar } = this.data
		const oldName = wx.getStorageSync('name')
		const oldIdentification = wx.getStorageSync('identification')
		const oldUsername = wx.getStorageSync('username')
		const oldPassword = wx.getStorageSync('password')
		const oldAvatar = wx.getStorageSync('avatar')
		if (
			oldName === name &&
			oldIdentification === identification &&
			oldUsername === username &&
			oldPassword === password &&
			oldAvatar === avatar
		) {
      wx.showToast({ title: '一样无需修改', icon: 'error', mask: true })
      return 0
		}
    wx.showLoading({ title: '修改中', mask: true })
    Serve.UpdateUser({ id, name, username, password, avatar, identification })
    wx.hideLoading()

    wx.setStorageSync('name', name)
    wx.setStorageSync('username', username)
    wx.setStorageSync('password', password)
    wx.setStorageSync('identification', identification)
    wx.setStorageSync('avatar', avatar)

    wx.navigateBack()
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		const _this = this
		const role = wx.getStorageSync('role')
		const openid = wx.getStorageSync('openid')

		wx.showLoading({ title: '获取用户信息', mask: true })
		Serve.GetUser({ role, openid }).then((result) => {
			const { name, username, password, identification, avatar, _id } = result
			_this.setData({
				name,
				username,
				password,
				identification,
				avatar,
				id: _id,
			})
		})
		wx.hideLoading()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {},
})
